package com.lu.adog.util.image;

import android.graphics.Bitmap;
import android.graphics.ImageFormat;

/**
 * @author Yue
 * @date 2017/11/17 17:53
 */

public class SimpleGray {
    private final static int MODE_AVG = 0;
    private final static int MODE_WEIGHT = 1;

    /**
     * rgb通道平均值去色
     *
     * @param image
     * @return 新的黑白化图片
     */
    public static Bitmap getAVGGray(Bitmap image) {
        return getGrayImage(image, MODE_AVG);
    }

        private static Bitmap getGrayImage(Bitmap image, int mode) {
        int width = image.getWidth();   //获取位图的宽
        int height = image.getHeight();  //获取位图的高

        Bitmap result = Bitmap.createBitmap(width, height, image.getConfig());

        int alpha = 0xff;
        int r = 0;
        int g = 0;
        int b = 0;

        int gray = 0;

        for (int i = 0; i < width; i++) {//一行行扫描
            for (int j = 0; j < height; j++) {

                gray = image.getPixel(i, j);

                alpha = gray >>> 24;
                r = (gray >> 16) & 0x000000ff;
                g = (gray >> 8) & 0x000000ff;
                b = gray & 0x000000ff;

                switch (mode) {
                    case MODE_AVG:
                        gray = (r + g + b) / 3;
                        break;
                    case MODE_WEIGHT:
                        gray = (int) (r * 0.299f + g * 0.587f + b * 0.114f);
                        break;
                    default:
                        gray = (int) (r * 0.299f + g * 0.587f + b * 0.114f);
                        break;
                }
                gray = (alpha << 24) | (gray << 16) | (gray << 8) | gray;

                result.setPixel(i, j, gray);
            }

        }
        return result;
    }
}
